package com.shelby.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class TestController {

    @GetMapping(value = "common")
    public String commonDemo() {
        log.info("common-start");
        String ret = doSome("common response");
        log.info("common-end");

        return ret;
    }

    /**
     * Mono 用法
     *
     * @return
     */
    @GetMapping("/mono")
    public Mono<String> monoDemo() {
        log.info("webflux-mono-start");
        Mono<String> ret = Mono.fromSupplier(() -> doSome("webflux-demo"));
        log.info("webflux-mono-end");

        return ret;
    }

    /**
     * 添加一个耗时操作用于测试上面的代码
     *
     * @param msg
     * @return
     */
    public String doSome(String msg) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return msg;
    }


    /**
     * Flux 用法1 -- 数组转 Flux
     *
     * @return
     */
    @GetMapping("/flux1")
    public Flux<String> flux1(@RequestParam String[] param) {
        Flux<String> flux = Flux.fromArray(param);

        return flux;
    }

    /**
     * Flux 用法2 -- 集合转 Flux
     *
     * @return
     */
    @GetMapping("/flux2")
    public Flux<String> flux2(@RequestParam List<String> param) {
        Flux<String> flux = Flux.fromStream(param.stream());

        return flux;
    }

    /**
     * Flux 用法3 --  Flux 底层不会阻塞处理器执行
     *
     * @return
     */
    @GetMapping("/flux3")
    public Flux<String> flux3(@RequestParam List<String> param) {
        log.info("flux-start");

        Flux<String> flux = Flux.fromStream(param.stream().map(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "param: " + i + " ";
        }));

        log.info("flux-end");

        return flux;
    }
}
